<template>
  <section v-loading.fullscreen.lock="loading">
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative">
        <el-row>
          <el-col
            :sm="24"
            :md="24"
            :lg="12"
            :xl="12"
            class="flex  align-center justify-start"
          >
            <span class="title-icon margin-right">箱单信息</span>
            <div>
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-download"
                @click="downPackingListInfo"
              >
                导出箱单信息
              </el-button>
              <el-button
                v-if="isEdit"
                type="primary"
                size="mini"
                icon="el-icon-upload2"
                @click="uploadDialog = true"
              >
                导入箱单信息
              </el-button>
            </div>
          </el-col>
          <el-col
            :sm="23"
            :md="23"
            :lg="11"
            :xl="11"
            class="flex text-blue align-center justify-between"
          >
            <div class="text-blue ">
              <span class="margin-lr">总箱数：{{ totalAmount[0] }} </span>
              <span class="margin-lr">总数量：{{ totalAmount[1] }} </span>
              <span class="margin-lr">总重量：{{ totalAmount[2] }} </span>
            </div>
            <div>
              <el-button
                v-if="isEdit && verifyShow.invoiceViewEdit"
                type="success"
                size="mini"
                @click="enter"
              >
                确认发货
              </el-button>
              <el-button
                v-if="isEdit && verifyShow.invoiceViewEdit"
                type="success"
                size="mini"
                @click="batchDel"
              >
                批量删除
              </el-button>
            </div>
          </el-col>
          <el-col
            :sm="1"
            :md="1"
            :lg="1"
            :xl="1"
            class="text-right flex align-center"
            style="justify-content: flex-end;"
          >
            <i
              :class="{
                'el-icon-arrow-down': show,
                'el-icon-arrow-up': !show
              }"
              class="text-lg pointer margin-left"
              @click="show = !show"
            />
          </el-col>
        </el-row>
      </div>

      <div>
        <el-table
          v-show="show"
          ref="multipleTable"
          :header-cell-style="{ background: '#f5f9fc' }"
          size="mini"
          border
          :data="tableData"
          :span-method="objectSpanMethod"
          style="width: 100%;"
          class="margin-top "
          tooltip-effect="light"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" align="center" />

          <ex-table-column
            v-for="column in tableColumns"
            :key="column.prop"
            :auto-fit="true"
            :fit-header="true"
            :prop="column.prop"
            :label="column.label"
          >
            <template slot-scope="scope" class="column-wrapper">
              <template v-if="column.type && column.type === 'boolean'">
                <el-select
                  v-if="verifyShow.returnInfoEdit"
                  v-model="scope.row[column.prop]"
                  placeholder="请选择"
                  size="mini"
                  @change="changeCargoInfo(scope)"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <span v-else>
                  {{
                    scope.row[column.prop] == 0
                      ? "否"
                      : scope.row[column.prop]
                      ? "是"
                      : ""
                  }}
                </span>
              </template>
              <template v-else>
                <el-input
                  v-if="verifyShow.returnInfoEdit"
                  v-model="scope.row[column.prop]"
                  size="mini"
                  @change="changeCargoInfo(scope)"
                />
                <span v-else>{{ scope.row[column.prop] }}</span>
              </template>
            </template>
          </ex-table-column>

          <el-table-column label="操作" width="60" align="center">
            <template slot-scope="scope">
              <i
                class="el-icon-delete padding-lr-sm pointer"
                @click="colDel(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <ImportPop
      :uploadDialog.sync="uploadDialog"
      :actionUrl="`batchUploadAbroadPackList`"
      :waybillId="waybillId"
      @uploadCb="uploadPackingInfo"
    ></ImportPop>
  </section>
</template>

<script>
import { clone } from "@/utils/clone";
import * as constant from "@/store/yg/common/constant";
import { ajax } from "@/store/yg/common/utils";
import ImportPop from "./ImportPop";
export default {
  name: "OrderToOrderToOverseasWarehouseShipping",
  components: {
    ImportPop
  },
  props: {
    packingList: {
      type: Array,
      default: function() {
        return [];
      }
    },
    actionUrl: {
      type: String,
      default: ""
    },
    waybillId: {
      type: Number,
      default: 1
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    verifyShow: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },

  data() {
    return {
      show: false,
      totalAmount: [0, 0, 0],
      uploadDialog: false,
      loading: false,
      autoHeight: "auto",
      waybillGoodsInfos: [{}, {}, {}, {}, {}],
      multipleSelection: [],
      tableData: [],
      spanArr: [],
      pos: 0,
      tableColumns: [
        {
          prop: "cartonNo",
          label: "箱号"
        },
        {
          prop: "oldSku", // 指定所指列
          label: "旧FNSKU"
        },
        {
          prop: "sku",
          label: "新FNSKU"
        },
        {
          prop: "num",
          label: "数量"
        },
        {
          prop: "weight",
          label: "重量"
        },
        {
          prop: "size",
          label: "外箱尺寸"
        }
      ]
    };
  },
  watch: {
    packingList: {
      handler(newValue, oldValue) {
        console.log("packingList :>> ", newValue);

        const arr = [];
        for (const i of newValue) {
          console.log("i :>> ", i);
          if(i.abroadNewSkus) {
            for (const j of i.abroadNewSkus) {
            arr.push({
              id: i.id,
              cartonNo: i.cartonNo,
              waybillId: i.waybillId,
              size: i.size,
              weight: i.weight,
              sku: j.sku,
              oldSku: j.oldSku,
              skuId: j.id,
              num: j.num
            });
          }
          }
          
        }
        console.log("arr :>> ", arr);
        this.tableData = arr;
        this.getSpanArr(this.tableData);
      },
      deep: true,
      immediate: true
    }
  },
  computed: {},
  mounted() {},
  methods: {
    // 计算表格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if ([0, 1, 5, 6].includes(columnIndex)) {
        // 关键字段  shipmentId 一定要存在
        const target = this.packingList.find(x => x.cartonNo === row.cartonNo);
        // console.log('target.spanArr[rowIndex] :>> ', target.spanArr[rowIndex])
        const row_span =
          target && (this.spanArr[rowIndex] || this.spanArr[rowIndex] === 0)
            ? this.spanArr[rowIndex]
            : 1;
        return {
          rowspan: row_span,
          colspan: 1
        };
      }
    },
    getSpanArr(arr) {
      // 数据排序，以便合并

      if (arr && arr.length > 0) {
        let spanArr = [];
        let pos = 0;

        arr.sort((a, b) => parseFloat(a.cartonNo) - parseFloat(b.cartonNo));
        spanArr = [];
        pos = 0;
        for (var i = 0; i < arr.length; i++) {
          if (i === 0) {
            spanArr.push(1);
            pos = 0;
          } else {
            // 判断当前元素与上一个元素是否相同,因合并第一个所以[0]
            if (arr[i]["cartonNo"] === arr[i - 1]["cartonNo"]) {
              spanArr[pos] += 1;
              spanArr.push(0);
            } else {
              spanArr.push(1);
              pos = i;
            }
          }
        }
        this.spanArr = spanArr;
        this.pos = pos;

        this.total();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    async batchDel() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择要删除的数据");
        return;
      }
      const ids = [];
      for (const s of this.multipleSelection) {
        ids.push(s.id);
      }

      this.$confirm("删除该信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.$store.dispatch("app/toggleDialog", true);

          const res = await ajax("batchDeletePackingList", {
            ids: ids
          });
          if (res.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success"
            });
            this.$emit("getPacking");
          } else {
            this.$message.error(res.message || "操作失败");
          }
          this.$store.dispatch("app/toggleDialog", false);
        })
        .catch(() => {});
    },
    async colDel(row) {
      this.$confirm("删除该信息, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.$store.dispatch("app/toggleDialog", true);

          const res = await ajax("deleteAbroadNewSkuById", {
            id: row.skuId
          });
          if (res.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success"
            });
            this.$emit("getPacking");
          } else {
            this.$message.error(res.message || "操作失败");
          }
          this.$store.dispatch("app/toggleDialog", false);
        })
        .catch(() => {});
    },
    total() {
      let boxs = 0;
      let amounts = 0;
      let weights = 0;
      let arr = [];
      for (const i of this.tableData) {
        if (i.cartonNo && !arr.includes(i.cartonNo)) {
          arr.push(i.cartonNo);
          if (i.weight) {
            weights += parseInt(i.weight);
          }
        }
        if (i.num && i.cartonNo) {
          amounts += Number(i.num);
        }
      }

      boxs = [...new Set(arr)].length;
      this.totalAmount = [boxs, amounts, weights];
    },
    closeDialog() {
      this.uploadDialog = false;
    },
    async downPackingListInfo() {
      const { path, fileName } = await ajax("downloadAbroadPackList", {
        id: this.waybillId
      });
      if (fileName) {
        window.open(constant.FILE_SERVER + fileName);
      }
    },
    uploadPackingInfo(file) {
      this.$emit("getPacking");
    },
    changeCargoInfo(s) {
      if (!s.row.cartonNo) {
        this.$message.error("请填写当前行箱数");
        return;
      }
      if (!s.row.oldSku) {
        this.$message.error("请填写当前行旧FNSKU");
        return;
      }
      if (!s.row.sku) {
        this.$message.error("请填写当前行新FNSKU");
        return;
      }
      if (!s.row.num) {
        this.$message.error("请填写当前行数量");
        return;
      }
      if (!s.row.weight) {
        this.$message.error("请填写当前行重量");
        return;
      }
      if (!s.row.size) {
        this.$message.error("请填写当前行Size");
        return;
      }
      const obj = {
        waybillId: this.waybillId,
        cartonNo: s.row.cartonNo,
        size: s.row.size,
        remark: s.row.remark,
        weight: s.row.weight,
        id: s.row.id,
        abroadNewSkus: [
          {
            id: s.row.skuId,
            oldSku: s.row.oldSku,
            packListId: s.row.id,
            sku: s.row.sku,
            num: s.row.num
          }
        ]
      };
      //  保存操作
      this.saveInfo(obj);
    },
    async saveInfo(obj) {
      this.loading = true;

      // return;
      const { code, message } = await ajax("saveAbroadPacking", {
        abroadPackingLists: [obj]
      });
      this.loading = false;
      if (code === 200) {
        this.$message({
          type: "success",
          message: "保存成功"
        });
        this.$emit("getPacking");
      } else {
        this.$message.error(message);
      }
    },

    async enter() {
      const arr = [];
      for (let i of this.packingList) {
        if (i.id && i.isSelect) {
          arr.push(i.id);
        }
      }

      if (arr.length === 0) {
        this.$message.error("没有符合的数据");
        return;
      }

      const data = await ajax("batchConfirmShipment", { ids: arr });
      if (data.code === 200) {
        this.$message.success("操作成功！");
      } else {
        this.$message.error(data.message || "操作失败！");
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.relative {
  .absolute {
    right: 10px;
    top: -40%;
  }
}
</style>
<style scoped>
/deep/ .el-card__header {
  padding: 8px 20px;
}
</style>
